package com.gct.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import com.gct.domain.Art;
import com.gct.persistence.ArtMapper;
import com.gct.service.base.BaseService;
import com.gct.view.dto.ArtStatisticsDto;

@Service
public class ArtService extends BaseService {
    @Autowired
    private ArtMapper artMapper;

    public List<Art> getArts() {
        return artMapper.getArts();
    }

    public List<Art> getArtsMostPlayed() {
        return artMapper.getArtsMostPlayed();
    }

    public List<Art> getArtsMostViewed() {
        return artMapper.getArtsMostViewed();
    }

    public List<Art> getArtsHighlyVoted() {
        return artMapper.getArtsHighlyVoted();
    }

    public Art getArtDetails(Long id) {
        return artMapper.getArtDetails(id);
    }

    public Art getArtURI(Long id) {
        return artMapper.getArtURI(id);
    }

    @Transactional(isolation=Isolation.READ_COMMITTED)
    public void saveArtStatics(List<ArtStatisticsDto> statisList) {
        List<ArtStatisticsDto> rs = queryArtStatics(statisList);
        if(!rs.isEmpty()) {
            for(ArtStatisticsDto a : rs)
                if(statisList.contains(a)) {
                    a.setStatisticsCollect(a.getStatisticsCollect() + statisList.get(statisList.indexOf(a)).getStatisticsCollect());
                    a.setStatisticsDownload(a.getStatisticsDownload() + statisList.get(statisList.indexOf(a)).getStatisticsDownload());
                    a.setStatisticsOpen(a.getStatisticsOpen() + statisList.get(statisList.indexOf(a)).getStatisticsOpen());
                    a.setStatisticsPlay(a.getStatisticsPlay() + statisList.get(statisList.indexOf(a)).getStatisticsPlay());
                }
        }
        for(ArtStatisticsDto ad : rs)
            artMapper.saveArtStatics(ad);
    }

    private List<ArtStatisticsDto> queryArtStatics(List<ArtStatisticsDto> statisList) {
        return artMapper.getArtStatsByIds(statisList);
    }
}
